import datetime
import pandas as pd
import jqdatasdk
from django.core.management.base import BaseCommand
from stocksys import models as stocksys_models


class Command(BaseCommand):
    help = 'create_conceptual_data_from_jqdata'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('清空概念数据'))
        stocksys_models.Concept.objects.all().delete()
        self.stdout.write(self.style.SUCCESS('验证远程数据密钥'))
        auth_key = None
        with open("data/auth_key.key") as key:
            auth_key = key.read().split(",")
            jqdatasdk.auth(auth_key[0], auth_key[1])
            print(auth_key)
        self.stdout.write(self.style.SUCCESS('请求远程数据'))
        data = jqdatasdk.get_concepts()
        data['code'] = data.index
        data.index = [x for x in range(len(data))]
        print(data.head())
        # data.to_csv('./data/Conceptual.csv', index=False)

        self.stdout.write(self.style.SUCCESS('载入概念数据'))
        for index in range(len(data)):
            row = data.loc[index].to_dict()
            concept=stocksys_models.Concept.objects.create(
                name=row['name'],
                code=row['code'],
                start_date=row['start_date'].to_pydatetime(),
            )
            stocks = jqdatasdk.get_concept_stocks(row['code'])
            for stock in stocks:
                stock = stock.split('.')
                stock_code = stock[0]
                exchange_abbreviated_name = stock[1]
                exchange_address = stocksys_models.ExchangeAddress.objects.get(stock_jqdata_name=exchange_abbreviated_name)

                # 获取股票所属概念
                stock_model = stocksys_models.Stock.objects.get(code=stock_code,
                                                                exchange_address=exchange_address)
                stocksys_models.StockConcept.objects.create(stock=stock_model, concept=concept)

        self.stdout.write(self.style.SUCCESS('结束载入'))
